﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace WeAppsCenterOnlineSetup
{
    internal class Downloader
    {
        [DllImport("msi.dll", CharSet = CharSet.Auto)]
        internal static extern uint MsiInstallProduct([MarshalAs(UnmanagedType.LPWStr)] string szPackagePath, [MarshalAs(UnmanagedType.LPWStr)] string szCommandLine);

        private void WebClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            Console.WriteLine("Downloading " + e.ProgressPercentage + "%");
        }

        public void Download(string url)
        {
            int index = url.LastIndexOf('/');
            string filename = Environment.CurrentDirectory + "\\" + url.Substring(index + 1);
            WebClient webClient = new WebClient();
            webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;
            webClient.DownloadFileAsync(new Uri(url), filename);
            while (webClient.IsBusy) { }
            webClient.Dispose();
            Install(filename);
        }
        private void Install(string filename)
        {
            //执行安装
            if (filename.EndsWith(".msi"))
            {
                MsiInstallProduct(filename, "ACTION=INSTALL");
                Console.WriteLine("Installation finished. Press any key to exit.");
            }
            else if (filename.EndsWith(".exe"))
            {
                Process process = new Process();
                process.StartInfo.FileName = filename;
                process.Start();
                process.WaitForExit();
            }
            //删除临时文件
            Program.Delete(filename);
        }
    }
}
